
# with open('bibtex.bib', 'w') as bibfile:
#     bibfile.write(bibtex)
import bibtexparser

with open('bibtex1.bib') as bibtex_file:
    bib_database = bibtexparser.load(bibtex_file)
# // 检查bib 格式是否正确
# // 类型 article book ..
article_set = {"ID","ENTRYTYPE","title", "author", "journal","volume","number","pages","year"}
book_set = {"ID","ENTRYTYPE","title","author","year","address","pages","publisher"}
# // title 首字母大写，其余小写，除了专有名词 NS Peterlin 存容器里面
title_check = set()
# // journal 则每个单词首字母大写，除了 for on 这些连词 存容器
journal_check = set()
# 缺少的文献ID和缺失字段组成字典
lack_fields = {}
for e in bib_database.entries:
    if e.get('ENTRYTYPE').strip() == 'article':
        for k in list(e.keys()):
# // 首先检查字段是否存在非规定字段，
            if k in article_set:
                strs =  e[k].replace('{',"").replace("}","").split(" ")
                if k.strip() == 'title':
                  for index in range(len(strs)):
                      if index != 0 and strs[index].istitle():
                          title_check.add(strs[index])
                          if strs[index] ==  "Methods":
                            print(e.get('ID'))
                if k.strip() == "journal":
                    for index in range(len(strs)):
                       if  strs[index].istitle() is False:
                           journal_check.add(strs[index])
                if len(e[k]) == 0:
                    lack_fields[e.get('ID')] = k
            else:
# // 如果存在非规定字段则删除，
                # 不属于该类型的字段就删除
                del e[k]
        if len(e.keys()) < len(article_set):
#             缺少字段,求差集，然后添加进去，默认值
            add_set = article_set.difference(set(e.keys()))
            for a in add_set:
# // 未添加字段先统一添加默认值，像address，number这些
                e[a] = ""
                lack_fields[e.get('ID')] = a
    if e.get('ENTRYTYPE').strip() == 'book':
        for k in list(e.keys()):
            if k in book_set:
                strs = e[k].replace('{', "").replace("}", "").split(" ")
                if k.strip() == 'title':
                    for index in range(len(strs)):
                        if index != 0 and strs[index].strip().istitle():
                            title_check.add(strs[index])
                if len(e[k]) == 0:
                    lack_fields[e.get('ID')] = k
            else:
                # 不属于该类型的字段就删除
                del e[k]
        if len(e.keys()) < len(book_set):
            #             缺少字段,求差集，然后添加进去，默认值
            add_set = book_set.difference(set(e.keys()))
            for a in add_set:
                e[a] = ""
                lack_fields[e.get('ID')] = a
print(title_check)
print(journal_check)
print(lack_fields)
with open('bibtex1.bib', 'w') as bibtex_file1:
    bibtexparser.dump(bib_database, bibtex_file1)